package net.caixiaomi.info.net;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import net.caixiaomi.info.R;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.logger.Timber;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.ui.login.LoginActivity;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 网络统一回调
 */

public abstract class ResponseCallback<T extends BaseCallModel> implements Callback<T> {
    private Context mContext;

    public ResponseCallback() {

    }

    public ResponseCallback(Context context) {
        mContext = context;
    }

    /**
     * 数据里code==0时回调该方法
     */
    public abstract void onSuccess(T data);

    /**
     * 数据里code！=0时回调该方法
     */
    public abstract void onFail(ResponseError error);

    /**
     * 网络异常
     */
    public abstract void onError();

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if (mContext != null) {
            Activity activity = (Activity) mContext;
            if (activity.isFinishing())
                return;
        }
        onError();
        ToastUtil.s(R.string.C_NET_ERROR);
        Timber.e(t.getLocalizedMessage());
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        try {
            if (mContext != null) {
                Activity activity = (Activity) mContext;
                if (activity.isFinishing())
                    return;
            }
            if (response.code() == 200) {
                T body = response.body();
                if (body != null) {
                    if (body.code != 0) {
                        if (body.code == 600) {
                            EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_LOGIN_OUT_RETURN_HOME));
                            CommonApp.removeUserInfo();
                            Intent intent = new Intent(mContext, LoginActivity.class);
                            mContext.startActivity(intent);
                        }
                        ResponseError error = new ResponseError(body.code, body.msg);
                        onFail(error);
                    } else {
                        onSuccess(body);
                    }
                } else {
                    ResponseError error = new ResponseError(-1, "");
                    onFail(error);
                }
            } else {
                ToastUtil.s(R.string.C_NET_FIX);
                onError();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
